package servic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"user-srv/basic/config"
	__ "user-srv/basic/proto"
	"user-srv/handler/model"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// 短信发送接口
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(9000) + 100
	result, _ := config.Rdb.Get(config.Ctx, "sendCode"+in.Phone).Result()
	if result >= "1" {
		return nil, fmt.Errorf("该短信只能一分钟发送一次")
	}
	//sms, _ := pkg.SendSms(in.Phone, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Phone, code, time.Minute*2)
	//短信发送限制一分钟
	val := config.Rdb.Incr(config.Ctx, "sendCode"+in.Phone).Val()
	if val == 1 {
		config.Rdb.Expire(config.Ctx, "sendCode"+in.Phone, time.Minute*1)
	}
	return &__.SendSmsResp{}, nil
}

// 登录注册一体化
// SayHello implements helloworld.GreeterServer
func (s *Server) LoginUser(_ context.Context, in *__.LoginUserReq) (*__.LoginUserResp, error) {
	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+in.Phone).Result()
	if result != in.Code {
		return nil, fmt.Errorf("验证码已失效,请重新输入")
	}
	var user model.User
	user.Phone = in.Phone
	config.DB.Where("phone=?", in.Phone).Find(&user)
	if user.ID == 0 {
		config.DB.Create(&user)
		return nil, fmt.Errorf("用户不存在,自动创建用户")
	}

	return &__.LoginUserResp{
		UserId: int64(user.ID),
	}, nil
}
